import mousetrap from 'mousetrap'
import { isArray, isFunction, isObject, isString } from 'lodash-es'
import { createDecorator } from './instantiation/instantiation'
import { registerSingleton, InstantiationType } from './instantiation/extensions'
import { runWhenIdle } from '@views/fabric/utils/async'

export const IKeybindingService = createDecorator('Keybinding');

export class Keybinding extends mousetrap {
  constructor() {
    super();
    this.mod = /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl';
  }

  /**
   * Overwrites default Mousetrap.bind method to optionally accept
   * an object to bind multiple key events in a single call
   *
   * You can pass it in like:
   *
   * Mousetrap.bind({
   *     'a': function() { console.log('a'); },
   *     'b': function() { console.log('b'); }
   * });
   *
   * And can optionally pass in 'keypress', 'keydown', or 'keyup'
   * as a second argument
   *
   */
  bind(keys, callbackOrAction, action) {
    if ((isString(keys) || isArray(keys)) && isFunction(callbackOrAction)) {
        return super.bind(keys, callbackOrAction, action);
    }
    if (isObject(keys) && !isArray(keys) && (!callbackOrAction || isString(callbackOrAction))) {
        for (const key in keys) {
            super.bind(key, keys[key], callbackOrAction);
        }
    }
    return this;
  }

  trigger(keys, action) {
    runWhenIdle(() => {
        super.trigger(keys, action);
    });
    return this;
  }
}

registerSingleton(IKeybindingService, Keybinding, InstantiationType.Eager)
